package control;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import com.itextpdf.text.DocumentException;

import persistence.PdfLoanReminder;
import view.components.Icons;
import domain.Customer;

public class ExportLoanRemindersHandler {
	JFileChooser fileChooser;
	String fileName = File.separator + "pdf";

	public ExportLoanRemindersHandler() {
		fileChooser = new JFileChooser(new File(fileName));
		fileChooser.removeChoosableFileFilter(fileChooser.getChoosableFileFilters()[0]);
		fileChooser.addChoosableFileFilter(new PDFFilter());
	}

	public void startExport(List<Customer> customers) {
		try {
			File file = askForDestinationFile();

			PdfLoanReminder reminder = new PdfLoanReminder(
					file.getAbsolutePath(), customers);
			try {
				reminder.createPDF();
				StatusMessageHandler.putMessage("Bericht erfolgreich exportiert");
			} catch (DocumentException e) {
				StatusMessageHandler.putMessage(
						"Bericht konnte nicht erzeugt werden", Icons.ERROR);
			} catch (IOException e) {
				StatusMessageHandler.putMessage(
						"Konnte \""+ file.getAbsolutePath() + "\" nicht speichern", Icons.ERROR);
			}
			
		} catch (IllegalArgumentException e) {
			StatusMessageHandler.putMessage("Berichterstellung abgebrochen");
		}
	}

	private File askForDestinationFile() throws IllegalArgumentException {
		if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if (!fileChooser.getFileFilter().accept(file)) {
				file = new File(file.getAbsoluteFile() + ".pdf");
			}
			return file;
		}
		throw new IllegalArgumentException();
	}

	private class PDFFilter extends FileFilter {
		public boolean accept(File file) {
			if(file.isDirectory()){
				return true;
			}
			String filename = file.getName();
			return filename.endsWith(".pdf");
		}

		public String getDescription() {
			return "*.pdf";
		}
	}
}
